<template>
    <div>
        <div class="w-form-header" style="min-height:26px">
            <div class="header" v-if="!pageLoading">
                <template
                    v-if="userStore.userInfo.authority?.authorityId !== 1000"
                >
                    <div v-if="!formData.status || formData.status == '0'">
                        <template v-if="isEditing">
                            <el-button type="primary" @click="isEditing = false"
                                >编辑</el-button
                            >
                        </template>
                        <template v-else>
                            <el-button
                                type="primary"
                                @click="save('0')"
                                :loading="saveLoading"
                                >保存</el-button
                            >
                            <el-button
                                type="success"
                                @click="save('1')"
                                :loading="submitLoading"
                                >提交</el-button
                            >
                        </template>
                    </div>
                    <div v-if="formData.status === '1'">
                        <el-button
                            type="success"
                            @click="editReasonDialogFun()"
                            :loading="submitLoading"
                            >修改</el-button
                        >
                    </div>
                </template>
                <div v-else></div>
                <div class="title-box" v-if="type == 'update'">
                    <span class="status">{{
                        formData.status == "1" ? "已確認" : "草稿"
                    }}</span>
                </div>
            </div>
        </div>
        <div class="admin-content">
            <div class="gva-form-box">
                <el-collapse v-model="activeNames" accordion>
                    <el-collapse-item name="1">
                        <template #title>
                            <div
                                class="w-form-box"
                                style="
                                    margin: 0;
                                    flex: 1;
                                    display: flex;
                                    justify-content: space-between;
                                "
                            >
                                <div
                                    class="list-header"
                                    style="margin-bottom: 0"
                                >
                                    基本信息
                                </div>
                                <div
                                    style="margin-right: 10px; font-size: 14px"
                                >
                                    {{ activeNames == 1 ? "收起" : "展开" }}
                                </div>
                            </div>
                        </template>
                        <el-descriptions
                            class="margin-top"
                            title=""
                            :column="4"
                            border
                        >
                            <el-descriptions-item
                                label-class-name="my-label"
                                class-name="my-content"
                            >
                                <template #label>
                                    <div class="cell-item">
                                        {{ `${il8n("kuanshibianhao1.label")}` }}
                                    </div>
                                </template>
                                <el-input
                                    v-model="formData.styleNum"
                                    :clearable="true"
                                    :placeholder="`${il8n(
                                        'kuanshibianhao1.placeholder'
                                    )}`"
                                    disabled
                                />
                            </el-descriptions-item>

                            <el-descriptions-item
                                label-class-name="my-label"
                                class-name="my-content"
                            >
                                <template #label>
                                    <div class="cell-item">
                                        {{ `${il8n("benchangkuanhao.label")}` }}
                                    </div>
                                </template>
                                <div
                                    style="
                                        display: flex;
                                        justify-content: center;
                                        width: 100%;
                                        justify-content: space-between;
                                    "
                                >
                                    <span>{{ formData.localStyleNum }}</span>
                                    <el-button
                                        type="primary"
                                        size="small"
                                        v-if="isEditing"
                                        @click="getGenLocalStyleNumFun"
                                        disabled
                                        :loading="updateLocalNumBtnLoading"
                                        >更新</el-button
                                    >
                                    <el-button
                                        type="primary"
                                        size="small"
                                        v-else="!isEditing"
                                        @click="getGenLocalStyleNumFun"
                                        :disabled="!!formData.localStyleNum"
                                        :loading="updateLocalNumBtnLoading"
                                        >更新</el-button
                                    >
                                </div>
                            </el-descriptions-item>

                            <el-descriptions-item
                                label-class-name="my-label"
                                class-name="my-content"
                            >
                                <template #label>
                                    <div class="cell-item">
                                        {{ `${il8n("kaibanshunxu.label")}` }}
                                    </div>
                                </template>
                                <el-select
                                    v-model="formData.establishOrder"
                                    :placeholder="`${il8n(
                                        'kaibanshunxu.placeholder'
                                    )}`"
                                    style="width: 100%"
                                    :clearable="true"
                                    filterable
                                    @change="establishOrderChange"
                                    :disabled="isEditing"
                                >
                                    <el-option
                                        v-for="(
                                            item, index
                                        ) in dictOptions.establishOrder"
                                        :key="index"
                                        :label="item.label"
                                        :value="item.value"
                                    />
                                </el-select>
                            </el-descriptions-item>

                            <el-descriptions-item
                                label-class-name="my-label"
                                class-name="my-content"
                            >
                                <template #label>
                                    <div class="cell-item">创建人</div>
                                </template>
                                <!-- {{ formData.createdUser?.nickName }} -->
                                <span
                                    v-if="
                                        formData.createdUser &&
                                        formData.createdUser.nickName
                                    "
                                >
                                    {{ formData.createdUser.nickName }}
                                </span>
                                <span v-else>{{ formData.createUser }}</span>
                            </el-descriptions-item>

                            <el-descriptions-item
                                label-class-name="my-label"
                                class-name="my-content"
                            >
                                <template #label>
                                    <div class="cell-item">
                                        {{ `${il8n("SBU.label")}` }}
                                    </div>
                                </template>
                                {{ formData.sbuNum }}
                            </el-descriptions-item>

                            <el-descriptions-item
                                label-class-name="my-label"
                                class-name="my-content"
                            >
                                <template #label>
                                    <div class="cell-item">
                                        {{ `${il8n("jingjiacaizhi.label")}` }}
                                    </div>
                                </template>
                                <el-select
                                    v-model="formData.frameMaterial"
                                    :placeholder="`${il8n(
                                        'jingjiacaizhi.placeholder'
                                    )}`"
                                    style="width: 100%"
                                    @change="frameMaterialsChange"
                                    :disabled="
                                        isEditing ||
                                        isModifyFrameMaterials == '0'
                                    "
                                    filterable
                                >
                                    <el-option
                                        v-for="(
                                            item, index
                                        ) in dictOptions.frameMaterials"
                                        :key="index"
                                        :label="item.label"
                                        :value="item.value"
                                    />
                                </el-select>
                            </el-descriptions-item>

                            <el-descriptions-item
                                label-class-name="my-label"
                                class-name="my-content"
                            >
                                <template #label>
                                    <div class="cell-item">
                                        {{ `${il8n("huitu.label")}` }}
                                    </div>
                                </template>
                                <el-select
                                    v-model="formData.drawer"
                                    :placeholder="`${il8n(
                                        'huitu.placeholder'
                                    )}`"
                                    style="width: 100%"
                                    :clearable="true"
                                    filterable
                                    @change="drawerChange"
                                    :disabled="isEditing"
                                >
                                    <el-option
                                        v-for="(
                                            item, index
                                        ) in dictOptions.drawer"
                                        :key="index"
                                        :label="item.label"
                                        :value="item.value"
                                    />
                                </el-select>
                            </el-descriptions-item>

                            <el-descriptions-item
                                label-class-name="my-label"
                                class-name="my-content"
                            >
                                <template #label>
                                    <div class="cell-item">创建时间</div>
                                </template>
                                {{
                                    formatDate(
                                        formData.CreatedAt,
                                        "yyyy-MM-dd hh:mm:ss"
                                    )
                                }}
                            </el-descriptions-item>

                            <el-descriptions-item
                                label-class-name="my-label"
                                class-name="my-content"
                            >
                                <template #label>
                                    <div class="cell-item">
                                        {{ `${il8n("kehubianhao.label")}` }}
                                    </div>
                                </template>
                                {{ formData.cumstomerNum }}
                            </el-descriptions-item>

                            <el-descriptions-item
                                label-class-name="my-label"
                                class-name="my-content"
                            >
                                <template #label>
                                    <div class="cell-item">
                                        {{ `${il8n("jingjialeibie.label")}` }}
                                    </div>
                                </template>
                                <el-select
                                    v-model="formData.glassFrameCate"
                                    :placeholder="`${il8n(
                                        'jingjialeibie.placeholder'
                                    )}`"
                                    style="width: 100%"
                                    :clearable="true"
                                    filterable
                                    :disabled="isEditing"
                                >
                                    <el-option
                                        v-for="(
                                            item, index
                                        ) in dictOptions.glassFrameCate"
                                        :key="index"
                                        :label="item.label"
                                        :value="item.value"
                                    />
                                </el-select>
                            </el-descriptions-item>

                            <el-descriptions-item
                                label-class-name="my-label"
                                class-name="my-content"
                            >
                                <template #label>
                                    <div class="cell-item">
                                        {{
                                            `${il8n(
                                                "gongchengshizuzhang.label"
                                            )}`
                                        }}
                                    </div>
                                </template>
                                <el-select
                                    v-model="formData.peLeader"
                                    :placeholder="`${il8n(
                                        'gongchengshizuzhang.placeholder'
                                    )}`"
                                    style="width: 100%"
                                    :disabled="isEditing"
                                    :clearable="true"
                                    filterable
                                >
                                    <el-option
                                        v-for="(item, key) in peLeaderOptions"
                                        :key="key"
                                        :label="`${item.nickName}(${item.userName})`"
                                        :value="item.userName"
                                    />
                                </el-select>
                            </el-descriptions-item>

                            <el-descriptions-item
                                label-class-name="my-label"
                                class-name="my-content"
                            >
                                <template #label>
                                    <div class="cell-item">更新人</div>
                                </template>
                                <!-- {{ formData.updatedUser?.nickName }} -->
                                <span
                                    v-if="
                                        formData.updatedUser &&
                                        formData.updatedUser.nickName
                                    "
                                >
                                    {{ formData.updatedUser.nickName }}
                                </span>
                                <span v-else>{{ formData.updateUser }}</span>
                            </el-descriptions-item>

                            <el-descriptions-item
                                label-class-name="my-label"
                                class-name="my-content"
                            >
                                <template #label>
                                    <div class="cell-item">
                                        {{ `${il8n("kehukuanhao.label")}` }}
                                    </div>
                                </template>
                                <el-input
                                    v-model="formData.customerStyleNum"
                                    :clearable="true"
                                    :placeholder="`${il8n(
                                        'kehukuanhao.placeholder'
                                    )}`"
                                    :disabled="isEditing"
                                />
                            </el-descriptions-item>

                            <el-descriptions-item
                                label-class-name="my-label"
                                class-name="my-content"
                            >
                                <template #label>
                                    <div class="cell-item">
                                        {{ `${il8n("yewuleibie.label")}` }}
                                    </div>
                                </template>
                                <el-select
                                    v-model="formData.businessCate"
                                    :placeholder="`${il8n(
                                        'yewuleibie.placeholder'
                                    )}`"
                                    style="width: 100%"
                                    :clearable="true"
                                    filterable
                                    :disabled="isEditing"
                                >
                                    <el-option
                                        v-for="(
                                            item, index
                                        ) in dictOptions.businessCate"
                                        :key="index"
                                        :label="item.label"
                                        :value="item.value"
                                    />
                                </el-select>
                            </el-descriptions-item>

                            <el-descriptions-item
                                label-class-name="my-label"
                                class-name="my-content"
                            >
                                <template #label>
                                    <div class="cell-item">
                                        {{ `${il8n("shejishi.label")}` }}
                                    </div>
                                </template>
                                <el-select
                                    v-model="formData.designer"
                                    :placeholder="`${il8n(
                                        'shejishi.placeholder'
                                    )}`"
                                    style="width: 100%"
                                    :clearable="true"
                                    filterable
                                    :disabled="isEditing"
                                >
                                    <el-option
                                        v-for="(item, key) in designerOptions"
                                        :key="key"
                                        :label="`${item.nickName}(${item.userName})`"
                                        :value="item.userName"
                                    ></el-option>
                                </el-select>
                            </el-descriptions-item>

                            <el-descriptions-item
                                label-class-name="my-label"
                                class-name="my-content"
                            >
                                <template #label>
                                    <div class="cell-item">更新时间</div>
                                </template>
                                {{
                                    formatDate(
                                        formData.UpdatedAt,
                                        "yyyy-MM-dd hh:mm:ss"
                                    )
                                }}
                            </el-descriptions-item>

                            <el-descriptions-item
                                label-class-name="my-label"
                                class-name="my-content"
                            >
                                <template #label>
                                    <div class="cell-item">
                                        {{ `${il8n("kehupinpai.label")}` }}
                                    </div>
                                </template>
                                <el-input
                                    v-model="formData.customerBrand"
                                    :clearable="true"
                                    :placeholder="`${il8n(
                                        'kehupinpai.placeholder'
                                    )}`"
                                    disabled
                                />
                            </el-descriptions-item>

                            <el-descriptions-item
                                label-class-name="my-label"
                                class-name="my-content"
                            >
                                <template #label>
                                    <div class="cell-item">
                                        {{ `${il8n("xilie.label")}` }}
                                    </div>
                                </template>
                                <el-input
                                    v-model="formData.series"
                                    :clearable="true"
                                    :placeholder="`${il8n(
                                        'xilie.placeholder'
                                    )}`"
                                    :disabled="isEditing"
                                />
                            </el-descriptions-item>

                            <el-descriptions-item
                                label-class-name="my-label"
                                class-name="my-content"
                            >
                                <template #label>
                                    <div class="cell-item">生产报价</div>
                                </template>
                                <!-- <el-select
                        v-model="formData.transferOrderRange"
                        :placeholder="`${il8n('shengchanbaojia.placeholder')}`"
                        style="width: 100%"
                        :clearable="true"
                        filterable
                        multiple
                        :disabled="isEditing"
                    >
                        <el-option
                            v-for="(item, index) in dictOptions.transferOrder"
                            :key="index"
                            :label="item.label"
                            :value="item.value"
                        >
                        <el-checkbox :label="item.label"
                                :value="item.value"  />
                    </el-option>
                    </el-select> -->
                                <el-tree-select
                                    v-model="formData.transferOrderRange"
                                    :data="
                                        dictOptions.transferOrder.filter(
                                            (item) => {
                                                if (
                                                    formData.cumstomerNum ==
                                                    'ST101'
                                                ) {
                                                    return (
                                                        item.extend == 'ST101'
                                                    );
                                                } else {
                                                    return (
                                                        item.extend == '其他'
                                                    );
                                                }
                                            }
                                        )
                                    "
                                    :disabled="isEditing"
                                    multiple
                                    :render-after-expand="false"
                                    show-checkbox
                                    style="width: 100%"
                                />
                                <!-- collapse-tags -->
                            </el-descriptions-item>

                            <!-- <el-descriptions-item
                        label-class-name="my-label"
                        class-name="my-content"
                    >
                        <template #label>
                            <div class="cell-item">
                                {{ `${il8n("faxingnian.label")}` }}
                            </div>
                        </template>
                        <el-select
                            v-model="formData.issuanceYear"
                            :placeholder="`${il8n('faxingnian.placeholder')}`"
                            style="width: 100%"
                            :clearable="true"
                            filterable
                            :disabled="isEditing"
                        >
                            <el-option
                                v-for="(
                                    item, index
                                ) in dictOptions.issuanceYear"
                                :key="index"
                                :label="item.label"
                                :value="item.value"
                            />
                        </el-select>
                    </el-descriptions-item>
                   
                    <el-descriptions-item
                        label-class-name="my-label"
                        class-name="my-content"
                    >
                        <template #label>
                            <div class="cell-item">
                                {{ `${il8n("faxingyue.label")}` }}
                            </div>
                        </template>
                        <el-select
                            v-model="formData.issuanceMonth"
                            :placeholder="`${il8n('faxingyue.placeholder')}`"
                            style="width: 100%"
                            :clearable="true"
                            filterable
                            :disabled="isEditing"
                        >
                            <el-option
                                v-for="(
                                    item, index
                                ) in dictOptions.issuanceMonth"
                                :key="index"
                                :label="item.label"
                                :value="item.value"
                            />
                        </el-select>
                    </el-descriptions-item>

                    <el-descriptions-item
                        label-class-name="my-label"
                        class-name="my-content"
                    >
                        <template #label>
                            <div class="cell-item">
                                {{ `${il8n("jingjiajiegou.label")}` }}
                            </div>
                        </template>
                        <el-select
                            v-model="formData.frameCate"
                            :placeholder="`${il8n(
                                'jingjiajiegou.placeholder'
                            )}`"
                            style="width: 100%"
                            :clearable="true"
                            filterable
                            :disabled="isEditing"
                        >
                            <el-option
                                v-for="(item, index) in dictOptions.frameCate"
                                :key="index"
                                :label="item.label"
                                :value="item.value"
                            />
                        </el-select>
                    </el-descriptions-item>

                    <el-descriptions-item
                        label-class-name="my-label"
                        class-name="my-content"
                    >
                        <template #label>
                            <div class="cell-item">
                                {{ `${il8n("pitouqiekouwei.label")}` }}
                            </div>
                        </template>
                        <el-select
                            v-model="formData.splenicHeadIncisionPosition"
                            :placeholder="`${il8n(
                                'pitouqiekouwei.placeholder'
                            )}`"
                            style="width: 100%"
                            :clearable="true"
                            filterable
                            :disabled="isEditing"
                        >
                            <el-option
                                v-for="(
                                    item, index
                                ) in dictOptions.splenicHeadIncisionPosition"
                                :key="index"
                                :label="item.label"
                                :value="item.value"
                            />
                        </el-select>
                    </el-descriptions-item>

                    <el-descriptions-item
                        label-class-name="my-label"
                        class-name="my-content"
                    >
                        <template #label>
                            <div class="cell-item">
                                {{ `${il8n("jingjiajingpian.label")}` }}
                            </div>
                        </template>
                        <el-select
                            v-model="formData.category"
                            :placeholder="`${il8n(
                                'jingjiajingpian.placeholder'
                            )}`"
                            style="width: 100%"
                            :clearable="true"
                            filterable
                            :disabled="isEditing"
                        >
                            <el-option
                                v-for="(item, index) in dictOptions.styleCate"
                                :key="index"
                                :label="item.label"
                                :value="item.value"
                            />
                        </el-select>
                    </el-descriptions-item>
                  
                    <el-descriptions-item
                        label-class-name="my-label"
                        class-name="my-content"
                    >
                        <template #label>
                            <div class="cell-item">
                                {{ `${il8n("chengbenhesuan.label")}` }}
                            </div>
                        </template>
                        <el-select
                            v-model="formData.costAccountCate"
                            :placeholder="`${il8n(
                                'chengbenhesuan.placeholder'
                            )}`"
                            style="width: 100%"
                            :clearable="true"
                            filterable
                            :disabled="isEditing"
                        >
                            <el-option
                                v-for="(
                                    item, index
                                ) in dictOptions.costAccountCate"
                                :key="index"
                                :label="item.label"
                                :value="item.value"
                            />
                        </el-select>
                    </el-descriptions-item> -->

                    <el-descriptions-item
                        label-class-name="my-label"
                        class-name="my-content"
                    >
                        <template #label>
                            <div class="cell-item">
                                {{ `${il8n("xingbie.label")}` }}
                            </div>
                        </template>
                        <el-select
                            v-model="formData.gender"
                            :placeholder="`${il8n('xingbie.placeholder')}`"
                            style="width: 100%"
                            :clearable="true"
                            filterable
                            :disabled="isEditing"
                        >
                            <el-option
                                v-for="(
                                    item, index
                                ) in dictOptions.productGender"
                                :key="index"
                                :label="item.label"
                                :value="item.value"
                            />
                        </el-select>
                    </el-descriptions-item> 

                  <!--  <el-descriptions-item
                        label-class-name="my-label"
                        class-name="my-content"
                    >
                        <template #label>
                            <div class="cell-item">
                                {{ `${il8n("jiaolianleibie.label")}` }}
                            </div>
                        </template>
                        <el-select
                            v-model="formData.hingeType"
                            :placeholder="`${il8n(
                                'jiaolianleibie.placeholder'
                            )}`"
                            style="width: 100%"
                            :clearable="true"
                            filterable
                            :disabled="isEditing"
                        >
                            <el-option
                                v-for="(item, index) in dictOptions.hingeType"
                                :key="index"
                                :label="item.label"
                                :value="item.value"
                            />
                        </el-select>
                    </el-descriptions-item> -->
                        </el-descriptions>
                    </el-collapse-item>
                </el-collapse>
            </div>
            <div class="gva-form-box">
                <div class="w-form-box">
                    <div class="list-header">计划日期</div>
                    <div>
                        <PlansData
                            ref="PlansDataRef"
                            :isEditing="isEditing"
                            :formData="formData"
                        />
                    </div>
                </div>
            </div>
            <div class="gva-form-box">
                <div class="w-form-box">
                    <div class="list-header">历史修改备注</div>
                    <el-table :data="formData.notes" border style="width: 100%">
                        <el-table-column
                            type="index"
                            label="序号"
                            width="80px"
                        />
                        <el-table-column
                            label="更改内容"
                            prop="content"
                        ></el-table-column>
                        <el-table-column label="更改原因" prop="reason">
                        </el-table-column>
                        <el-table-column
                            label="详细说明"
                            prop="detail"
                        ></el-table-column>
                        <el-table-column label="更新时间" prop="">
                            <template #default="scope">
                                <span>
                                    {{
                                        formatDate(
                                            scope.row.UpdatedAt,
                                            "yyyy-MM-dd hh:mm:ss"
                                        )
                                    }}
                                </span>
                            </template>
                        </el-table-column>
                        <el-table-column label="更新人" prop="updateUser">
                        </el-table-column>
                    </el-table>
                </div>
            </div>
        </div>

        <!-- 添加修改备注 -->
        <el-dialog
            v-model="editReasonDialogShow"
            destroy-on-close
            width="50%"
            title="添加修改备注"
        >
            <el-form ref="editReasonDialogRef" inline :model="editReasonForm">
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="内容分类：">
                            <el-checkbox-group v-model="editReasonForm.content">
                                <el-checkbox
                                    v-for="item in contentCateOptions"
                                    :key="item.value"
                                    :label="item.label"
                                    :value="item.value"
                                    style="width: 100%"
                                />
                            </el-checkbox-group>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="原因分类：">
                            <el-checkbox-group v-model="editReasonForm.reason">
                                <el-checkbox
                                    v-for="item in reasonCateOptions"
                                    :key="item.value"
                                    :label="item.label"
                                    :value="item.value"
                                    style="width: 100%"
                                />
                            </el-checkbox-group>
                        </el-form-item>
                    </el-col>
                    <el-col :span="24">
                        <el-form-item label="详细说明：" style="width: 100%">
                            <textarea
                                v-model="editReasonForm.detail"
                                :rows="5"
                                style="width: 90%"
                            />
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button type="primary" @click="save('0', 'edit')"
                        >确定</el-button
                    >
                    <el-button @click="editReasonDialogShow = false"
                        >取消</el-button
                    >
                </div>
            </template>
        </el-dialog>
    </div>
</template>

<script setup>
import LTable from "@/components/LTable/LTable.vue";
import {
    createProductStyles,
    deleteProductStyles,
    deleteProductStylesByIds,
    updateProductStyles,
    findProductStyles,
    getProductStylesList,
    generateProductStylesPlan,
    getGenLocalStyleNum,
} from "@/api/plmProductStyles";
import { findSbuProjects } from "@/api/plmSbuProjects";
import { getProjectPlanList } from "@/api/plmProjectPlan";
import { getUserList } from "@/api/user";
import { findSbuData } from "@/api/confSbuData";

// 全量引入格式化工具 请按需保留
import { formatDate } from "@/utils/format";
import PlansData from "./PlansData.vue";

const PlansDataRef = ref();

defineOptions({
    name: "plmProductStylesView",
});

// 自动获取字典
import { getDictFunc } from "@/utils/format";
import { useDict } from "@/utils/dictionary.js";
import { emitter } from "@/utils/bus.js";
import { useRoute, useRouter } from "vue-router";
import { ElMessage } from "element-plus";
import { ref, reactive, onMounted, computed } from "vue";
import { useI18n } from "vue-i18n";
import { useUserStore } from "@/pinia/modules/user";
import { deepClone2 } from "@/utils/tool.js";
const userStore = useUserStore();

const { t: il8n } = useI18n();

const route = useRoute();
const router = useRouter();

const type = ref("");
const sbuTypesOptions = ref([]);
const loading = ref(false);
const sbuOptions = ref([]); // sbu列表
const customerOptions = ref([]); // 客户编号列表
const brandOptions = ref([]); // 品牌列表
const saveLoading = ref(false); // 保存草稿状态
const submitLoading = ref(false); // 提交状态
const activeNames = ref("1");
const formData = ref({
    frameMaterial: "",
});

// 字典列表
const dictOptions = ref({
    establishOrder: [], //開辦順序
    glassFrameCate: [], //镜架类别
    drawer: [], // 绘图
    frameCate: [], // 款式資訊-架類
    styleCate: [], // 款式資訊-類別
    costAccountCate: [], //成本核算分類
    frameMaterials: [], //镜架材质
    productGender: [], //款式資訊-性別
    splenicHeadIncisionPosition: [], //脾頭切口位
    hingeType: [], //鉸鏈類別
    businessCate: [], //業務類別
    issuanceMonth: [], //業務月
    issuanceYear: [], //業務年
    transferOrder: [], // 转单
});
const peLeaderOptions = ref([]); // 工程师组长列表
const designerOptions = ref([]); // 设计师列表

const oldFrameMaterial = ref(""); // 旧镜架材质
const oldLocalStyleNum = ref(""); // 旧本厂款号
const oldLocalStyleNumObj = ref({}); // 旧本厂款号列表

const isModifyFrameMaterials = ref(""); // 旧本厂款号列表
// 验证规则
const rule = reactive({
    frameMaterial: [
        { required: true, message: "请选择镜架材质", trigger: "change" },
    ],
});

const elFormRef = ref();

// 计划日期
const planListData = ref([]);
const viewModel = ref(""); // 查看方式

const projectPlans = ref([]);

const isEditing = ref(false);
const pageLoading = ref(true);

// 初始化方法
const init = async () => {
    // 建议通过url传参获取目标数据ID 调用 find方法进行查询数据操作 从而决定本页面是create还是update 以下为id作为url参数示例
    if (route.query.id) {
        oldFrameMaterial.value = null;
        oldLocalStyleNum.value = null;
        oldLocalStyleNumObj.value = {};
        // formData.value = {};
        pageLoading.value = true;
        findProductStyles({ ID: route.query.id })
            .then(async (res) => {
                pageLoading.value = false;
                if (res.code === 0) {
                    formData.value = res.data.reproductStyles;
                    if (!!formData.value.localStyleNum) {
                        oldFrameMaterial.value = formData.value.frameMaterial;
                        oldLocalStyleNum.value = formData.value.localStyleNum;
                        oldLocalStyleNumObj.value[
                            formData.value.frameMaterial
                        ] = formData.value.localStyleNum;
                    }
                    // if (
                    //     !formData.value.localStyleNum &&
                    //     !!formData.value.frameMaterial
                    // ) {
                    //     updateLocalNumBtn.value = false;
                    // }
                    updateLocalNumBtn.value = true;
                    type.value = "update";
                    // formData.value.projectPlans.forEach((item) => {
                    //     item["planCycle"] = item["lifeCycle"];
                    // });
                    PlansDataRef.value.updateValue(formData.value.projectPlans);
                    dataNumChange();
                    if (res.data.reproductStyles.status == 0) {
                        const projectsRes = await findSbuProjects({
                            projectNum: res.data.reproductStyles.projectNum,
                        });
                        let oldSbuName = formData.value.sbuNum;
                        const { sbuName, customerName, brandName } =
                            projectsRes.data.resbuProjects;
                        if (sbuName) {
                            formData.value.sbuNum = sbuName;
                        }
                        if(oldSbuName != sbuName){
                            formData.value['designer'] = ''
                            formData.value['peLeader'] = ''
                        }
                        if (customerName) {
                            formData.value.cumstomerNum = customerName;
                        }
                        if (brandName) {
                            formData.value.customerBrand = brandName;
                        }
                    }
                    findSbuDataFun(formData.value.sbuNum);
                    isModifyFrameMaterials.value =
                        res.data.isModifyFrameMaterials;
                }
            })
            .catch((err) => {
                pageLoading.value = false;
            });
    } else {
        type.value = "create";
    }
    // sbuTypesOptions.value = await getDictFunc("sbuTypes");
};

init();

// 获取sbu信息
const findSbuDataFun = (sbuNum) => {
    findSbuData({ sbuName: sbuNum }).then((res) => {
        if (res.data.resbuData.members) {
            designerOptions.value = res.data.resbuData.members;
            peLeaderOptions.value = res.data.resbuData.members;
        }
    });
};

// 查询
const getPlanListData = async () => {
    const table = await generateProductStylesPlan();
    if (table.code === 0) {
        // planListData.value = table.data.list;
    }
};

const updateLocalNumBtn = ref(true); // 更新按钮状态
const updateLocalNumBtnLoading = ref(false);
const frameMaterialsChange = () => {
    // updateLocalNumBtn.value = false;
    if (oldLocalStyleNumObj.value[formData.value.frameMaterial]) {
        formData.value.localStyleNum =
            oldLocalStyleNumObj.value[formData.value.frameMaterial];
    } else {
        formData.value.localStyleNum = null;
    }
};

// 更新本厂款号
const getGenLocalStyleNumFun = () => {
    if (!formData.value.frameMaterial) {
        ElMessage({
            type: "warning",
            message: "请选择镜架材质再更新",
        });
        return;
    }
    updateLocalNumBtnLoading.value = true;
    getGenLocalStyleNum({
        cumstomerNum: formData.value.cumstomerNum,
        frameMaterial: formData.value.frameMaterial,
    })
        .then((res) => {
            updateLocalNumBtnLoading.value = false;
            if (res.code == 0) {
                formData.value.localStyleNum = res.data.localStyleNum;
                oldFrameMaterial.value = formData.value.frameMaterial;
                updateLocalNumBtn.value = true;
                oldLocalStyleNumObj.value[formData.value.frameMaterial] =
                    formData.value.localStyleNum;
            }
        })
        .catch((err) => {
            updateLocalNumBtnLoading.value = false;
        });
};

const sumDay = (dateStr, days) => {
    const date = new Date(dateStr);
    date.setDate(date.getDate() + days);
    return date.toISOString();
};

// 时间改变plannedStartDate,plannedCompletionDate
const dataNumChange = () => {
    projectPlans.value.forEach((item, index) => {
        if (index != 0) {
            if (item.related == "1") {
                let data1 = sumDay(
                    projectPlans.value[0].plannedCompletionDate,
                    1
                );
                item["plannedStartDate"] = data1;
                let data2 = sumDay(data1, +item.planCycle);
                item["plannedCompletionDate"] = data2;
            } else {
                if (item.nodeIndex != item.related) {
                    let i = projectPlans.value.findIndex((d) => {
                        return item.related == d.nodeIndex;
                    });
                    let data1 = projectPlans.value[i].plannedCompletionDate;
                    item["plannedStartDate"] = data1;
                    let data2 = sumDay(data1, +item.planCycle);
                    item["plannedCompletionDate"] = data2;
                }
            }
        }
    });
};

// 修改备注模块
const editReasonDialogShow = ref(false);
const contentCateOptions = ref([]);
const reasonCateOptions = ref([]);
const editReasonForm = ref({
    content: [],
    reason: [],
    detail: "",
});
const historyNoteTableData = ref([]);
// 修改备注弹窗
const editReasonDialogFun = async () => {
    if (!formData.value.frameMaterial) {
        ElMessage({
            type: "warning",
            message: "镜架材质不能为空",
        });
        return;
    }
    editReasonDialogShow.value = true;
    editReasonForm.value = {
        content: [],
        reason: [],
        detail: "",
    };
    // 获取词典
    const options = await useDict("contentCate", "reasonCate");
    contentCateOptions.value = options.contentCate;
    reasonCateOptions.value = options.reasonCate;
};

const reload = ref(false);
const reloadPage = () => {
    reload.value = true;
    emitter.emit("reload");
    setTimeout(() => {
        reload.value = false;
    }, 500);
};

// 保存按钮
const save = async (status, editStatus) => {
    if (status == "1" && !formData.value.frameMaterial) {
        ElMessage({
            type: "warning",
            message: "镜架材质不能为空",
        });
        return;
    }
    if (status == "1" && !formData.value.drawer) {
        ElMessage({
            type: "warning",
            message: "绘图不能为空",
        });
        return;
    }
    if (status == "1" && !formData.value.establishOrder) {
        ElMessage({
            type: "warning",
            message: "开办顺序不能为空",
        });
        return;
    }
    if (
        status == "1" &&
        (!formData.value.transferOrderRange ||
            formData.value.transferOrderRange.length == 0)
    ) {
        ElMessage({
            type: "warning",
            message: "生产报价不能为空",
        });
        return;
    }

    // 新需求,鹏飞加:ST101的系列提交时设为必填
    if (formData.value.cumstomerNum == "ST101" && !formData.value.series) {
        ElMessage({
            type: "warning",
            message: "系列不能为空",
        });
        return;
    }

    // if (status == "1" && !formData.value.localStyleNum) {
    //     ElMessage({
    //         type: "warning",
    //         message: "本厂款号不能为空",
    //     });
    //     return;
    // }
    editReasonDialogShow.value = false;
    let res;
    let submitForm = Object.assign({}, formData.value);
    if (editStatus == "edit") {
        // 修改备注
        submitForm["notes"] = [
            {
                content: editReasonForm.value.content.join(","),
                reason: editReasonForm.value.reason.join(","),
                detail: editReasonForm.value.detail || "",
            },
        ];
    }
    submitForm["status"] = status;
    let planList = deepClone2(PlansDataRef.value.projectPlans)
    submitForm["projectPlans"] = planList.map((item) => {
        item["planned_completion_date"] = new Date(
            item["planned_completion_date"]
        ).toJSON();
        item["planned_start_date"] = new Date(
            item["planned_start_date"]
        ).toJSON();
        return item;
    });

    if (status === "0") saveLoading.value = true;
    if (status === "1") submitLoading.value = true;
    res = await updateProductStyles(submitForm);
    saveLoading.value = false;
    submitLoading.value = false;
    if (res.code === 0) {
        // emitter.emit("closeThisPage", { path: "/layout/productStyles" });
        ElMessage({
            type: "success",
            message: "更改成功",
        });
        if (editStatus == "edit") {
            isEditing.value = false;
        }
        if (status == "0") {
            init();
        } else {
            emitter.emit("closeThisPage", {
                path: "/layout/productStyles",
            });
        }
    }
};

// 开办顺序改变
const establishOrderChange = () => {
    PlansDataRef.value.establishOrderChange();
};
// 绘图改变
const drawerChange = () => {
    PlansDataRef.value.drawerChange();
};

onMounted(async () => {
    const dict = await useDict(
        "establishOrder",
        "glassFrameCate",
        "drawer",
        "frameCate",
        "styleCate",
        "costAccountCate",
        "frameMaterials",
        "productGender",
        "splenicHeadIncisionPosition",
        "hingeType",
        "businessCate",
        "issuanceYear",
        "issuanceMonth",
        "transferOrder"
    );
    dictOptions.value = Object.assign(dictOptions.value, dict);
    if (route.query.action == "v") {
        isEditing.value = true;
    } else {
        isEditing.value = false;
    }
});
</script>

<style lang="scss" scoped>
@import url("@/style/common/common.scss");

.gva-form-box {
    :deep(.my-label) {
        width: 9%;
    }

    :deep(.my-content) {
        width: 16%;
    }
}

.title-box {
    display: flex;
    align-items: center;

    .title {
        font-size: 20px;
        font-weight: 600;
        margin-right: 8px;
    }
}

:deep(.el-collapse-item__content) {
    padding-bottom: 0;
}
</style>
